import React from 'react';
import ReactDOM from 'react-dom';
import { registerMicroApps, setDefaultMountApp, start } from 'qiankun'
// import subApps from './sub-app.config'
import htmlParse from './utils/htmlParse'
import { getConfig } from './services'

const subApps = [{
  name: 'reactApp',
  entry: '//localhost:3000/',
  container: '#subapp-viewport',
  activeRule: '/app-react',
}]

const { APP_ENV } = process.env
const isEnvLocal = APP_ENV === 'local'

/**
 * 渲染子应用
 */
function App(props) {
  const { loading } = props;

  return (
    <>
      {loading && <h4 className="subapp-loading">Loading...</h4>}
      <div id="subapp-viewport" />
    </>
  );
}

function render({ loading }) {
  const container = document.getElementById('subapp-container');
  ReactDOM.render(<App loading={loading} />, container);
}

const loader = loading => render({ loading });

render({ loading: true })

// registerMicroApps(subApps.map(app => ({
//   name: app.name,
//   entry: app.entrys[APP_ENV || 'prod'],
//   container: '#subapp-viewport',
//   activeRule: app.activeRules[APP_ENV || 'prod'],
//   loader,
// })))

registerMicroApps(subApps)

const getVersion = isEnvLocal ? () => new Promise(resolve => resolve({ data: {} })) : getConfig


getVersion().then(res => {

  start({

    // 是否开启预加载 因为本地多为localhost 所以不开启
    prefetch: false,

    // 对jsonp不做处理
    excludeAssetFilter(assetUrl) {
      if (assetUrl.indexOf('callback=') !== -1) return true
      return false
    },

    // 开启沙箱后 微应用在window上挂在的方法都会代理到window.proxy
    // sandbox: false,
    sandbox: { loose: true },

    getTemplate: htmlTemplate => isEnvLocal ? htmlTemplate : htmlParse(htmlTemplate, res.data)
  })
})



